<?php
class Pageley_Controller_Dispatcher_Http extends Pageley_Controller_Dispatcher_Basic {
	public function __construct() {
        parent::__construct(new Pageley_Controller_ViewResolver_Html());
        $this->setNotFoundHandler(new Pageley_Controller_Dispatcher_Http_ErrorHandler("404", "Not Found", "error.notFound.title"));
        $this->setErrorHandler(new Pageley_Controller_Dispatcher_Http_ErrorHandler("500", "Internal Server Error", "error.server.title"));
	}

	protected function initializeRequest() {
		ob_start();
		session_start();
		if(array_key_exists("HTTP_ACCEPT_LANGUAGE", $_SERVER)) {
			$localeString = $_SERVER["HTTP_ACCEPT_LANGUAGE"];
			$locales = new Pageley_Util_ArrayMap();
			if($localeString) {
				$localeParts = preg_split("/,/",$localeString);
			    foreach($localeParts as $part) {
					$loc = "";
					$part = trim($part);
					$locale = null;
					if(preg_match("/;/", $part)) {
					    $loc = preg_split("/;/", $part);
					    $part = $loc[0];
					}
					$locale = $this->getLocale($part);
					if(Pageley_Log::isDebugEnabled($this)) {
						Pageley_Log::debug($this, "Adding locale '" . $part ."'.");
					}
					$locales->add($locale);
			    }
			}
			$_SESSION["pageley.locales"] = $locales;
		}
	}

	protected function getLocale($localeExpression) {
		$locale = null;
		$locParts = preg_split("/-/", $localeExpression);
		if(count($locParts) > 1) {
			$locale = new Pageley_I18n_Locale(
				$locParts[0],
				strtoupper($locParts[1])
			);
		} else {
			$locale = new Pageley_I18n_Locale(
				$locParts[0]
			);
		}
		return $locale;
	}
    
    protected function resolveView($view) {
        $this->getViewResolver()->resolveView($view);
        ob_end_flush();
    }
    
    protected function resolveErrorView() {
    	ob_clean();
        $this->getViewResolver()->resolveView($this->getErrorView());
        ob_end_flush();
    }
}